﻿/**************************************************************
*作者：Leon
*创建时间：2022/1/8 11:26:51
**************************************************************/
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace StudentManagement.Controllers
{
    public class ErrorController:Controller
    {
        private readonly ILogger<ErrorController> logger;
        /// <summary>
        /// 通过ASP.Net Core依赖注入服务注入ILogger服务
        /// 将指定类型的控制器作为泛型参数
        /// </summary>
        /// <param name="logger"></param>
        public ErrorController(ILogger<ErrorController> logger)
        {
            this.logger = logger;
        }
        [Route("Error/{statusCode}")]
        public IActionResult HttpStatusCodeHandler(int statusCode)
        {
            var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();

            switch (statusCode)
            {
                case 404:
                    ViewBag.ErrorMessage = "抱歉，您访问的页面不存在";
                    ViewBag.Path = statusCodeResult.OriginalPath;
                    ViewBag.QueryStr = statusCodeResult.OriginalQueryString;
                    ViewBag.BasePath = statusCodeResult.OriginalPathBase;
                    logger.LogError(statusCodeResult.OriginalPath + "抱歉，您访问的页面不存在");
                    break;
            }
            return View("NotFound");
        }

        [AllowAnonymous]//允许匿名访问
        [Route("Error")]
        public IActionResult Error()
        {
            var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
            ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
            ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;
            logger.LogError(exceptionHandlerPathFeature.Error, "");
            return View("Error");
        }
    }
}
